package com.snaildesign.countdown.web;

import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.util.List;
import org.apache.commons.fileupload.FileUploadException;
import java.util.Iterator;
import org.apache.commons.fileupload.FileItem;
import java.io.File;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.ObjectUtils;

public class FileUploadAction extends HttpServlet{
    private static Logger logger = Logger.getLogger(FileUploadAction.class.getName());

    private int maxPostSize = 100 * 1024 * 1024;
    private String uploadPath = "D:\\upload\\";


    public FileUploadAction() {
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
        logger("begin upload");
        try {
			request.setCharacterEncoding("UTF-8");
				} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        response.setContentType("text/html; charset=UTF-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 4);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(maxPostSize);

        logger("request================"+ObjectUtils.toString(request));
        List fileItems = null;
        try {
            fileItems = upload.parseRequest(request);
            logger("===================="+ObjectUtils.toString(fileItems));
            Iterator iter = fileItems.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                log(item.toString());
                if (!item.isFormField()) {
                    String name = item.getName();
                    logger("file name = "+name);
                    try {
                        item.write(new File(uploadPath + name));
                    }
                    catch (Exception ex) {
                        logger(ex.getMessage());
                    }
                }
            }
        }
        catch (FileUploadException ex1) {
            logger("FileUploadException->"+ex1.getMessage());
        }


    }

    private void logger(String info){
        System.out.println(info);
    }

}
